package com.imooc.web.filter;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 
 * @author JZH
 * 
 * 当使用第三方过滤器的时候，我们无法使用@Component，因此，可以使用代码注入Filter
 * 
 * Filter的局限：本身是J2EE规范接口，而Controller是SpringMVC定义的一套规则，
 * 				 Filter无法知晓请求具体被哪一个Controller、哪一个方法处理。
 */
//@Component
public class RequestLogFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("【过滤器】初始化...");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		LocalDateTime startTime = LocalDateTime.now();
		System.out.println("【过滤器】开始时间："+startTime);
		LocalDateTime endTime = LocalDateTime.now();
		System.out.println("【过滤器】结束时间："+endTime);
		Duration duration = Duration.between(startTime, endTime);
		Long d = duration.toMillis();
		System.out.println("【过滤器】耗时："+d);
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("【过滤器】销毁...");
	}

}
